
import java.awt.Desktop;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;


public class ConfigFrame extends javax.swing.JFrame {
    private Twitter twitter;
    private RequestToken requestToken;
    private AccessToken accessToken = null;
    /** Creates new form ConfigFrame */
    public ConfigFrame() {
        initComponents();
         twitter = new TwitterFactory().getInstance();
         try {
         twitter.setOAuthConsumer("TuSvVl1GoSbSWoL0Hm0Pg", "rtNqaOH3rP96PeCvhkfVQR49KaxONDOfeyCRyKmbQRM");
         requestToken = twitter.getOAuthRequestToken();
         setVisible(true);
        } catch (IllegalStateException ie) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new testWindow(get_tw()).setVisible(true);
                }
            });
        } catch (TwitterException ex) {
        
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        jButton1 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBounds(new java.awt.Rectangle(100, 100, 700, 500));
        setResizable(false);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/tuitelo1.jpg"))); // NOI18N

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel2.setText("BIENVENIDO A TUITELO!");

        jTextPane1.setBackground(new java.awt.Color(240, 240, 240));
        jTextPane1.setEditable(false);
        jTextPane1.setText("Bienvenido a Tuitelo, el cliente Twitter de ELO329\n\nPara que la aplicación pueda ser ejecutada, son necesarios\nalgunos permisos que usted debe entregar. \n\nAl hacer clic en el boton inferior se abrirá una ventana de su \nnavegador donde debera ingresar con su cuenta de Twitter.\nUna vez que acepte dar los permisos se le entregará un PIN,\nque deberá escribir en el cuadro de texto inferior. ");
        jTextPane1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jTextPane1.setFocusable(false);
        jScrollPane1.setViewportView(jTextPane1);

        jButton1.setFont(new java.awt.Font("Tahoma", 0, 12));
        jButton1.setText("Dar permiso a Tuitelo");
        jButton1.setFocusPainted(false);
        jButton1.setMaximumSize(new java.awt.Dimension(160, 20));
        jButton1.setMinimumSize(new java.awt.Dimension(160, 20));
        jButton1.setPreferredSize(new java.awt.Dimension(160, 20));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel3.setText("PIN:");

        jTextField1.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jTextField1.setToolTipText("ingrese el pin...");
        jTextField1.setPreferredSize(new java.awt.Dimension(50, 20));

        jButton2.setFont(new java.awt.Font("Tahoma", 0, 12));
        jButton2.setText("INTENTAR CONECTAR");
        jButton2.setMaximumSize(new java.awt.Dimension(160, 20));
        jButton2.setMinimumSize(new java.awt.Dimension(160, 20));
        jButton2.setPreferredSize(new java.awt.Dimension(160, 20));
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel4.setText("Paso 1: Entregue Permisos a Tuitelo (se abrira su navegador por defecto)");

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel5.setText("Paso 2: Ingrese el PIN proporcionado por la pagina web");

        jLabel6.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel6.setText("Paso 3: Intente conectar Tuitelo a su cuenta de Twitter");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel5)
                    .addComponent(jLabel6)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 71, Short.MAX_VALUE)
                .addComponent(jLabel1))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel1)
            .addGroup(layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addComponent(jLabel2)
                .addGap(27, 27, 27)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(51, 51, 51)
                .addComponent(jLabel4)
                .addGap(3, 3, 3)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel5)
                .addGap(7, 7, 7)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            Desktop.getDesktop().browse(new URI(requestToken.getAuthorizationURL()));
        } catch (IOException ex) {
        } catch (URISyntaxException ex) {
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        String PIN = jTextField1.getText();
        try {
                                if (PIN.length() > 0) {
                                    accessToken = twitter.getOAuthAccessToken(requestToken,PIN);
                                }
                            } catch (TwitterException te) {
                                if (401 == te.getStatusCode()) {
                                } else {
                                }
                            }
        if(accessToken!=null){
            try {
                File file = new File("twitter4j.properties");
                Properties prop = new Properties();
                OutputStream os = new FileOutputStream(file);
                prop.setProperty("oauth.consumerKey", "TuSvVl1GoSbSWoL0Hm0Pg");
                prop.setProperty("oauth.consumerSecret", "rtNqaOH3rP96PeCvhkfVQR49KaxONDOfeyCRyKmbQRM");
                prop.setProperty("oauth.accessToken", accessToken.getToken());
                prop.setProperty("oauth.accessTokenSecret", accessToken.getTokenSecret());
                prop.store(os, "twitter4j.properties");
                os.close();
                JOptionPane.showMessageDialog(null, "Felicidades! esta listo para utilizar twitelo", "Configuracion Finalizada", JOptionPane.INFORMATION_MESSAGE);
                setVisible(false);
                java.awt.EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        new twiteloVentana(get_tw()).setVisible(true);
                    }
                });
            } catch (IOException ex) {
            }
        }
        else  JOptionPane.showMessageDialog(null, "El PIN ingresado no es valido.", "ERROR!", JOptionPane.ERROR_MESSAGE);

    }//GEN-LAST:event_jButton2ActionPerformed

    /**
    * @param args the command line arguments
    */

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration//GEN-END:variables
public Twitter get_tw(){
        return twitter;
    }
}
